package edu.nuist.unit01;

/**
 * @author wangzhuangzhuang
 * @DESC: 串行和并行执行Demo
 * @date 2022-04-19 22:06
 */
public class ConcurrencyTest {
	private static final long count = 10000L;

	public static void main(String[] args) throws InterruptedException {
		concurrency();
		serial();
	}

	private static void concurrency() throws InterruptedException {
		long start = System.currentTimeMillis();
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				int a = 0;
				for (long i = 0; i < count; i++) {
					a += 5;
				}
			}
		});
		thread.start();
		int b = 0;
		for (long i = 0; i < count; i++) {
			b--;
		}
		long time = System.currentTimeMillis() - start;
		thread.join(); // ★★★join()方法的作用： 让调用join()方法的线程在执行完run()方法之后，再执行join()方法后面的线程
		System.out.println("concurrency: " + time + "ms, b= " + b);
	}

	private static void serial() {
		long start = System.currentTimeMillis();
		int a = 0;
		for (long i = 0; i < count; i++) {
			a += 5;
		}
		int b = 0;
		for (long i = 0; i < count; i++) {
			b--;
		}
		long time = System.currentTimeMillis() - start;
		System.out.println("serial: " + time + "ms,b=" + b + ",a=" + a);
	}

}

//concurrency: 1ms, b= -10000
//serial: 0ms,b=-10000,a=50000

// 当并发执行累加操作不超过百万次时，速度会比串行执行累加操作要慢
// 为什么并发执行的速度有时候会比串行慢呢？ ====》 因为多线程操作需要有【创建线程和上下文切换的开销。】